<template>
  <Dialog
      :show="dialogConfig.show"
      :title="dialogConfig.title"
      :buttons="dialogConfig.buttons"
      :showCancel="true"
      width="80%"
      @close="dialogConfig.show = false"
  >
    <el-form
        :model="formData"
        :rules="rules"
        ref="formDataRef"
        label-width="80px"
        @submit.prevent
    >
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="标题" prop="title">
            <el-input :maxLength="10" v-model="formData.title"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="分类" prop="categoryId">
            <CategorySelect
                v-model="formData.categoryId"
                :type="0"
            ></CategorySelect>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="难度" prop="difficultyLevel">
            <el-rate v-model="formData.difficultyLevel"></el-rate>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="问题详情" prop="content">
            <SunEditor :height="450" v-model="formData.question"></SunEditor>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="答案解析" prop="answerAnalysis">
            <SunEditor :height="450" v-model="formData.answerAnalysis"></SunEditor>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </Dialog>
</template>


<script setup>
import {getCurrentInstance, nextTick, ref} from "vue";

const {proxy} = getCurrentInstance();

const formData = ref({});
const formDataRef = ref();
const rules = {
  title: [{required: true, message: "请输入标题"}],
  categoryId: [{required: true, message: "请选择分类"}],
  difficultyLevel: [{required: true, message: "请输选择难度"}],
  answerAnalysis: [{required: true, message: "请输入答案解析"}],
}

const emit = defineEmits()

const showEdit = (data) => {
  dialogConfig.value.show = true;
  nextTick(() => {
    dialogConfig.value.title = data.questionId ? '修改问题' : '添加问题'
    formData.value = Object.assign({}, data);
  })
}

// 编辑问题
const editQuestion = async () => {
  formDataRef.value.validate(async (valid) => {
    if (!valid) {
      return;
    }
    let params = {...formData.value};
    let result = await proxy.Request({
      url: "/questionInfo/saveQuestionInfo",
      params,
    })
    if (!result) {
      return;
    }
    proxy.Message.success(`${formData.value.questionId ? '修改' : '添加'}问题成功`);
    // proxy.Message.success(`添加问题成功`);
    formData.value = '';
    dialogConfig.value.show = false;
    emit("reload");
  })
}

// 配置
const dialogConfig = ref({
  show: false,
  buttons: [{
    text: "确定",
    type: "primary",
    click: editQuestion
  }],
  title: "添加问题",
  showClose: true
});

defineExpose({
  showEdit
})
</script>


<style scoped lang="scss">

</style>
